import functools
import hashlib
from pymongo import MongoClient
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from fastapi import *
from fastapi.responses import JSONResponse
from typing import Optional

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

client = MongoClient("mongodb://localhost:27017")
db = client["apitools"]
users_collection = db["users"]


class User:
    def __init__(self, username: str, password: str):
        self.username = username
        self.password_hash = self._hash_password(password)

    def verify_password(self, password: str):
        return password == self.password_hash

    def _hash_password(self, password: str):
        salt = "9529"  # 添加盐增加复杂度
        password = password.encode() + salt.encode()
        password_hash = hashlib.sha256(password).hexdigest()
        return password_hash


SECRET_KEY = "9527"


def create_access_token(data: dict):
    token = jwt.encode(data, SECRET_KEY, algorithm="HS256")

    return token


# 路由登录验证装饰器


def login_check(router_function):
    @functools.wraps(router_function)
    async def wrapper(request: Request, *args, **kwargs):
        try:
            cookie_value = request.cookies.get("token")
            user_level = int(kwargs.get('level', 4))
            if cookie_value:
                payload = jwt.decode(cookie_value, '9527', algorithms="HS256")
                username = payload.get('username')
                # 在此处进行其他验证逻辑，例如用户名和密码验证等
                user = users_collection.find_one({"username": username})
                level = int(user.get('level', 4))
                if level > user_level:
                    return JSONResponse(status_code=401, content={"status": "用户权限不足", "msg": "用户权限不足"})

                if user:
                    return await router_function(request,  *args, **kwargs)
                else:
                    return JSONResponse(status_code=401, content={"status": "不存在该用户", "msg": "不存在该用户"})
        except:
            pass
        return JSONResponse(status_code=401, content={"status": "请登录", "msg": "请登录"})

    return wrapper


def jwt_info(request):
    cookie_value = request.cookies.get("token")
    if cookie_value:
        payload = jwt.decode(cookie_value, '9527', algorithms="HS256")
        return payload
